require("../../assets/css/normalize.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/iconfont.css");
require("./sport_running.less");
// 引入模块
let dom = require("../../utils/dom.js");
let axios = require("../../utils/axios.js");
let date = require("../../utils/date.js");
document.addEventListener("DOMContentLoaded", function () {
	// 3. 地理定位
	AMap.plugin("AMap.Geolocation", function () {
		var geolocation = new AMap.Geolocation({
			// 是否使用高精度定位，默认：true
			enableHighAccuracy: true,
			// 设置定位超时时间，默认：无穷大
			timeout: 10000,
			// 定位按钮的停靠位置的偏移量
			offset: [10, 20],
			//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
			zoomToAccuracy: true,
			//  定位按钮的排放位置,  RB表示右下
			position: "RB",
		});

		geolocation.getCurrentPosition(function (status, result) {
			if (status == "complete") {
				console.log("定位成功", result);
			} else {
				console.log("定位失败");
			}
		});
	});
	// 2.点击暂停按钮,隐藏自己,显示暂停和结束
	dom.get("#pause").addEventListener("click", function () {
		dom.get("#pause").style.display = "none";
		dom.get("#continue").style.display = "block";
		dom.get("#end").style.display = "block";
		clearInterval(timer); //清除定时器标识，停止计时
	});
	// 1.点击继续按钮,隐藏自己和结束按钮,显示暂停
	dom.get("#continue").addEventListener("click", function () {
		dom.get("#continue").style.display = "none";
		dom.get("#end").style.display = "none";
		dom.get("#pause").style.display = "block";
		open(); //继续执行定时器
	});

	//4. 计算距离
	var p1 = [104.065751, 30.657453];
	var p2 = [116.397455, 39.909187];
	var dis = AMap.GeometryUtil.distance(p1, p2);
	// 5.通过定时器模拟跑步数据
	let duration = 0;
	let calorie = 0;
	let meter = 0;
	let timer = null;

	// 封装一个函数控制定时器的开关
	function open() {
		timer = setInterval(function () {
			// 每一秒都要获取数据-速度
			let speed = GetRandom(3, 7);
			// console.log(speed);
			dom.get("#spd").textContent = speed + "m/s";
			// 获取时间
			duration++;
			dom.get("#tme").textContent = date.getHms(duration);
			// 获取总跑步里程
			meter += speed;
			dom.get("#mileageNumber").textContent = (meter / 1000).toFixed(3);
			// 获取卡路里
			calorie = 50 * (meter / 1000) * 1.036;
			dom.get("#calo").textContent = calorie.toFixed(2); //保留两位小数
		}, 1000);
	}
	open();
	// 获取两个数之间的随机数
	function GetRandom(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}
	//6. 点击结束,推出并返回上一页
	dom.get("#end").addEventListener("click", function () {
		axios
			.post("/api/exercise/save", {
				type: 0,
				duration,
				calorie,
				meter,
			})
			.then(res => {
				// console.log(res);
				if (res.data.errno === 0) {
					alert("跑步结束!");
					history.back();
				}
			});
	});
});
